package com.noah.common.jasypt.aspect;

import com.noah.common.jasypt.annotation.Jasypt;
import com.noah.common.jasypt.enums.AlgoEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author noah
 * 2023/9/12 19:48
 */
@Aspect
@Component
@Slf4j
public class AesAspect {
    public AesAspect() {
        System.out.println("aesAspect 构造函数");
    }

    @Before("@annotation(com.noah.common.jasypt.annotation.Jasypt)")
    public void before(JoinPoint point) {
        System.out.println("注解执行前处理");
    }

    @After("@annotation(com.noah.common.jasypt.annotation.Jasypt)")
    public void after(JoinPoint joinPoint) {
        System.out.println("注解执行后处理");
    }

    @AfterThrowing(value = "@annotation(com.noah.common.jasypt.annotation.Jasypt)", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) {
        System.out.println("注解抛出异常时触发");
    }

    @AfterReturning(value = "@annotation(com.noah.common.jasypt.annotation.Jasypt)", returning = "returningValue")
    public void afterReturning(JoinPoint joinPoint, Object returningValue) {
        System.out.println("返回结果时触发");
    }

    @Around("@annotation(com.noah.common.jasypt.annotation.Jasypt)")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class returnType = signature.getReturnType();
        Class methodReturnType = method.getReturnType();
        AnnotatedType annotatedType = method.getAnnotatedReturnType();

        Jasypt jasypt = AnnotationUtils.findAnnotation(method, Jasypt.class);

        Object proceed = point.proceed();
        if (Objects.requireNonNull(jasypt).type() == AlgoEnum.AES) {
            // 对返回值进行加密处理
//            if(proceed instanceof result)
        }
        return proceed;
    }
}
